package com.strongbj.iot.devices.dam.response.handle.v1;

import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.device.Device;
import com.strongbj.core.device.DeviceManager;
import com.strongbj.core.device.IDevice;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.dam.common.NetMapping;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.smarrack.response.entity.DeviceEntity;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 心跳处理
 * 
 * @author yuzhantao
 *
 */
public class HeartbeatHandle extends DAMV1Handle {
	private static Logger logger = LogManager.getLogger(DoorStateHandle.class.getName());
	private final static String DEVICE_ONLINE_ACTION_CODE = "device_online"; // 设备在线的code
	private final static String RFID_TYPE = "damDc";
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private DAMMessage currentDAM; // 用于记录当前设备的信息
//	private DAMMessageFactory factory=new DAMMessageFactory();
	private boolean isFirstHeartbeat = true; // 是否是设备连接后的第一次接收心跳

	public HeartbeatHandle(DAMMessage currentDAM) {
		this.currentDAM = currentDAM;
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DAMMessage t) {

//		byte[] datas = factory.createDAMMessage(new byte[]{0,0,0,0,0,0,0,0}, t.getAddressCode(), (byte)0x01, (byte)1, (byte)0x01, new byte[0]);
//		logger.info("回复心跳:"+ByteUtil.byteArrToHexString(datas,true));
//		ByteBuf bs = Unpooled.copiedBuffer(datas);
//		ctx.channel().writeAndFlush(bs);

		logger.info("DAM设备 接收到网络心跳 {}", ctx.channel().remoteAddress().toString());
		// 将主机编号映射到网络通道中(将机柜编号和IP一一对应)
		NetMapping.getInstance().addChannelMapping(ByteUtil.byteArrToHexString(t.getAddressCode()), ctx.channel());
//		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		// TODO 拷贝读取到的编号到全局变量（解决DAM硬件上报屏幕命令时，上报的硬件编号为000001的问题）
		synchronized (this.currentDAM) {
			System.arraycopy(t.getAddressCode(), 0, this.currentDAM.getAddressCode(), 0, 3);
		}

		String ip = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
		IDevice dev = DeviceManager.getInstance().findDevice(ip);
		String deviceCode = ByteUtil.byteArrToHexString(t.getAddressCode());
		if (dev != null) {
			dev.setDeviceCode(deviceCode);
//			logger.info("DAM设备 接收到网络心跳 更新设备 IP={}  deviceCode={}", insocket.getAddress().getHostAddress(),deviceCode);
		} else {
			dev = new Device(deviceCode, ip);
			DeviceManager.getInstance().registerDevice(dev);
//			logger.info("DAM设备 接收到网络心跳 添加设备 IP={}  deviceCode={}", insocket.getAddress().getHostAddress(),deviceCode);
		}

		// 如果是连接后第一次接收心跳，则向mq发送设备连线信息
		if (this.isFirstHeartbeat) {
			this.pushDeviceOnlineMessageToMQ(deviceCode, ip);
			this.isFirstHeartbeat = false;
		}
		return null;
	}

	@Override
	protected boolean isHandleDAMMessage(DAMMessage t) {
		if (t.getCommand() == 0x01) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 推送设备联机信息到MQ
	 */
	private void pushDeviceOnlineMessageToMQ(String deviceCode, String ip) {
		MQMessageOfDAM msg = new MQMessageOfDAM();
		msg.setActioncode(DEVICE_ONLINE_ACTION_CODE);
		msg.setDevType(RFID_TYPE);

		DeviceEntity dev = new DeviceEntity();
		dev.setDeviceCode(deviceCode);
		dev.setIp(ip);
		msg.setAwsPostdata(dev);
		String json = JSON.toJSONString(msg);
		topicSender.send("damCommandToService", json);
		logger.info("上传DAM设备初始化在线信息=" + json);
	}
}
